<template>
  <div class="container">
    <div class="charts">
      <div v-if="currentChart === 'gender'" ref="genderChart" class="chart-container"></div>
      <div v-if="currentChart === 'age'" ref="ageChart" class="chart-container"></div>
      <div v-if="currentChart === 'ranking'" ref="rankingChartLeft" class="chart-container1"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    activeChart: {
      type: Object,
    },
  },
  data() {
    return {
      currentChart: "age",
      buttons: [
        { key: "gender", label: "案件性质" },
        { key: "age", label: "回复方式" },
      ],
      chartData: {
        age_analysis: ["78", "25", "20", "5", "5"],
        gender_analysis: [
          { value: 20, name: "控告案件" },
          { value: 7, name: "申诉案件" },
          { value: 1, name: "民事监督" },
          { value: 4, name: "行政监督" },
        ],
        age_data: ["短信", "电话", "书面", "匿名", "无法回复"],
        ranking_analysis: ["100", "47", "12", "10"],

        scenery: ["来信", "来访", "来电", "网络"],
        flowLeft: {
          regions: ["来信", "来访", "来电", "网络"],
          values: ["100", "47", "12", "10"],
        },
      },
      updateInterval: 5000,
      updateTimer: null,
      chartSwitchTimer: null,
      maxPoints: 20,
    };
  },
  watch: {
    activeChart(newCHART) {
      this.currentChart = newCHART;
      this.initCharts();
    },
  },
  mounted() {
    this.fetchChartData();
    this.$nextTick(() => {
      this.fetchChartData();
      // this.startUpdating();
      window.addEventListener("resize", this.resizeCharts);
    });
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.resizeCharts);
    this.disposeCharts();
    clearInterval(this.updateTimer);
    clearInterval(this.chartSwitchTimer);
  },
  methods: {
    OpenTime() {
      const chartKeys = this.buttons.map((button) => button.key);
      let index = chartKeys.indexOf(this.currentChart);

      this.chartSwitchTimer = setInterval(() => {
        index = (index + 1) % chartKeys.length;
        this.showChart(chartKeys[index]);
      }, 15000);
    },
    fetchChartData() {
      this.$axios
        .get("/api/screen/letterStatistics")
        .then((res) => {
          if (res.data.data) {
            const data = res.data.data;
            this.chartData = {
              gender_analysis: data.nature_case.name.map((name, index) => ({
                value: data.nature_case.value[index],
                name: name,
              })),
              age_analysis: data.reply_mode.value || [],
              age_data: data.reply_mode.name || [],
            };
            this.initCharts();
          }
        })
        .catch((error) => {
          console.error("Failed to fetch chart data:", error);
        });
    },
    // startUpdating() {
    //   this.updateTimer = setInterval(this.updateData, this.updateInterval);
    // },
    initCharts() {
      this.disposeCharts();
      this.$nextTick(() => {
        if (this.currentChart === "gender") this.initGenderChart();
        if (this.currentChart === "age") this.initAgeChart();
      });
    },
    showChart(chart) {
      this.currentChart = chart;
      this.initCharts();
    },
    resizeCharts() {
      if (this.genderChart) this.genderChart.resize();
      if (this.ageChart) this.ageChart.resize();
    },
    initGenderChart() {
      if (!this.chartData.gender_analysis.length) return;
      if (this.genderChart) this.genderChart.dispose();
      this.genderChart = echarts.init(this.$refs.genderChart);
      const option = {
        color: [
          "rgba(238, 153, 85, 1)",
          "rgba(65, 126, 255, 1)",
          "rgba(1, 219, 222, 1)",
          "rgba(147, 112, 219, 1)",
          "rgba(147, 112, 219, 1)",
        ],
        title: {
          text: "答复形式",
          show: false,
          left: "center",
          textStyle: {
            color: "#fff",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          show: true,
          left: "center",
          top: "0",
          bottom: "0",
          textStyle: { color: "#fff" },
        },
        series: [
          {
            name: "案件性质",
            type: "pie",
            radius: ["15%", "36%"],
            center: ["50%", "50%"],
            label: {
              normal: {
                show: false,
                formatter: (params) => {
                  var total = this.chartData.gender_analysis.reduce(
                    (sum, item) => sum + item.value,
                    0
                  );
                  var percent =
                    ((params.value / total) * 100).toFixed(0) + "%";
                  const index = params.dataIndex;
                  return [
                    `{normal${index}|${params.name}：}{normal${index}|${percent}}`,
                  ].join("\n");
                },
                padding: [0, 0],
                rich: this.getRich(),
              },
              emphasis: {
                show: true,
              },
            },
            labelLine: {
              lineStyle: {
                color: "#fff",
              },
              length: 20,
              length2: 20,
            },
            data: this.chartData.gender_analysis,
          },
          {
            radius: ["15%", "18%"],
            center: ["50%", "50%"],
            type: "pie",
            label: {
              normal: {
                show: false,
              },
              emphasis: {
                show: false,
              },
            },
            labelLine: {
              normal: {
                show: false,
              },
              emphasis: {
                show: false,
              },
            },
            animation: false,
            tooltip: {
              show: false,
            },
            data: [
              {
                value: 1,
                itemStyle: {
                  color: "rgba(37,109,137,0.22)",
                },
              },
            ],
          },
          {
            name: "外边框",
            type: "pie",
            clockWise: false,
            hoverAnimation: false,
            center: ["50%", "50%"],
            radius: ["39%", "39%"],
            label: {
              normal: {
                show: false,
              },
            },
            data: [
              {
                value: 9,
                name: "",
                itemStyle: {
                  normal: {
                    borderWidth: 2,
                    borderColor: "rgba(126,158,255,0.43)",
                  },
                },
              },
            ],
          },
        ],
      };
      this.genderChart.setOption(option);
    },
    getRich() {
      const colorArr = [
        "rgba(238, 153, 85, 1)",
        "rgba(65, 126, 255, 1)",
        "rgba(1, 219, 222, 1)",
        "rgba(147, 112, 219, 1)",
        "rgba(147, 112, 219, 1)",
      ];
      let result = {};
      colorArr.forEach((v, i) => {
        result[`normal${i}`] = {
          fontSize: 16,
          align: "left",
          padding: [30, 4, 0, 0],
          color: "#fff",
          fontFamily: "PingFang",
        };
      });
      return result;
    },
    initAgeChart() {
      if (!this.chartData.age_analysis.length) return;
      if (this.ageChart) this.ageChart.dispose();
      this.ageChart = echarts.init(this.$refs.ageChart);
      const option = {
        title: {
          text: "年龄分析",
          show: false,
          left: "center",
          textStyle: { color: "#fff" },
        },
        grid: {
          top: "30px",
          left: "10px",
          bottom: "10%",
          containLabel: true,
        },
        tooltip: { trigger: "axis" },
        xAxis: {
          type: "category",
          data: this.chartData.age_data,
          axisLine: { lineStyle: { color: "#fff" } },
          axisLabel: {
            color: "#fff",
            fontSize: 10,
          },
        },
        yAxis: {
          type: "value",
          axisLine: { lineStyle: { color: "#fff" } },
          splitLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1)",
            },
          },
          axisLabel: {
            color: "#fff",
            fontSize: 12,
            interval: 0,
          },
        },
        series: [
          {
            data: this.chartData.age_analysis,
            type: "line",
            barWidth: 5,
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#00f4fd" },
                  { offset: 1, color: "#00f4fd" },
                ]),
              },
            },
            areaStyle: {
              // 添加渐变阴影
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  // 设置渐变色
                  offset: 0,
                  color: "rgba(0, 198, 186, 1)", // 开始颜色
                },
                {
                  offset: 1,
                  color: "rgba(0, 136, 198, 0)", // 结束颜色
                },
              ]),
            },

          },
        ],
      };
      this.ageChart.setOption(option);
    },
    disposeCharts() {
      if (this.genderChart && !this.genderChart.isDisposed()) {
        this.genderChart.dispose();
      }
      if (this.ageChart && !this.ageChart.isDisposed()) {
        this.ageChart.dispose();
      }
    },
  },
};
</script>

<style scoped>
.container {
  width: 1050px;
  height: 300px;
  margin: 0 !important;
  padding: 0 !important;
}

.tabs {
  display: flex;
  font-size: 25px;
  margin-top: 9px;
  margin-left: 14px;
}

.tab {
  width: 80px;
  height: 20px;
  color: #d8f0ff;
  text-align: center;
  text-shadow: 0px 0px 4px #0091ff, 0px 0px 10px #0091ff;
  font-family: "PingFang SC";
  font-size: 12px;
  font-style: normal;
  font-weight: 400;
  line-height: 16px;
  border-radius: 3px;
  margin-left: 15px;
  cursor: pointer;
  border: 1px solid rgba(30, 123, 214, 0.22);
  background: linear-gradient(180deg,
      rgba(15, 74, 159, 0) 0%,
      rgba(17, 75, 160, 0.95) 137.5%);

  &.active {
    /* background-image: url("../../../public/imgs/choosebutton.png"); */
    border: 1px solid rgba(30, 123, 214, 1) !important;
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
}

.charts {
  /* margin-top: -15px; */
  margin-left: 10px;
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.chart-container {
  width: 100%;
  height: 250px;
  margin-left: 20px;
}

.chart-container1 {
  width: 100%;
  height: 225px;
}
</style>
